package com.chaoyong.higo.adapter;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.MainActivity;
import com.chaoyong.higo.activity.ProductDeTimeActivity;
import com.chaoyong.higo.adapter.FragAllGoodsAdapter.OnCartClick;
import com.chaoyong.higo.base.BaseRecyclerAdapter;
import com.chaoyong.higo.bean.ListEntity;
import com.chaoyong.higo.bean.LimShopBean.DataEntity;
import com.chaoyong.higo.cainiaowo.CartProvider;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.TransferTool;
import com.chaoyong.higo.utils.Values;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LimShopAdapter2 extends BaseRecyclerAdapter<DataEntity> {
	
	private SetHolderListener holderListener;
	private Context mContext;
	
	private CartProvider cartProvider;
	private OnCartClick click;

	public LimShopAdapter2(Context context) {
		super(context);
		this.mContext = context;
		cartProvider = new CartProvider(context);
	}

	BitmapUtils utils ;
	@Override
	public ViewHolder onCreate(ViewGroup parent, int viewType) {
		View layout = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_limshop, parent, false);
		utils = new BitmapUtils(parent.getContext());
		return new LimShopHolder(layout);
	}

	@Override
	public void onBind(final ViewHolder viewHolder, final int realPosition, final List<DataEntity> data) {
		if (viewHolder instanceof LimShopHolder) {
			
			int price = TransferTool.Strtoint(data.get(realPosition).getGoods_price(), ".");
			int count = data.get(realPosition).getSurplus();
//			Double pro = (double) ((price - count) / (price / 100));
			//Double pro = (double) (((price - count) / price) * 100);
			Double pro = (double) ((price - count) / (price / 100.00));
			((LimShopHolder) viewHolder).price_tx.setText(data.get(realPosition).getGoods_price());
			((LimShopHolder) viewHolder).total_tx.setText(TransferTool.toString(price));
			((LimShopHolder) viewHolder).count_tx.setText(TransferTool.toString(price - count));
			((LimShopHolder) viewHolder).left_tx.setText(TransferTool.toString(count));
			if(pro < 1 && pro > 0){
				((LimShopHolder) viewHolder).count_Pro.setProgress(1);
			}else{
				((LimShopHolder) viewHolder).count_Pro.setProgress(pro.intValue());
			}
			
			((LimShopHolder) viewHolder).item_limshop_xg.setText("限购\n" + data.get(realPosition).getLimit_buy_num() + "人次");
			
			utils.display(((LimShopHolder) viewHolder).image_img, Values.BASE_IMAGE_URL + data.get(realPosition).getCover_img().get(0));
			((LimShopHolder) viewHolder).cart_imgbt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					/*if (holderListener != null) {
						int[] start_location = new int[2];
						((LimShopHolder) viewHolder).image_img.getLocationInWindow(start_location);// 获取点击商品图片的位置
						Drawable drawable = ((LimShopHolder) viewHolder).image_img.getDrawable();// 复制一个新的商品图标
						// mHolderClickListener.onHolderClick(drawable,start_location);
						holderListener.SetOnClinck(drawable, start_location);
					}*/
					//DataEntity dataa = data.get(realPosition);
					ListEntity entity = new ListEntity();
					String s = data.get(realPosition).getAuto_release();
					entity.setAuto_release(s);
					entity.setCover_img(data.get(realPosition).getCover_img().get(0));
					String t = data.get(realPosition).getExpect();
					entity.setExpect(t);
					List<String> r = data.get(realPosition).getCover_img();
					entity.setFace_img(r );
					entity.setGoods_expect(data.get(realPosition).getGoods_expect());
					entity.setGoods_id(data.get(realPosition).getGoods_id());
					entity.setGoods_info(data.get(realPosition).getGoods_info());
					entity.setGoods_name(data.get(realPosition).getGoods_name());
					entity.setGoods_price(Double.parseDouble(data.get(realPosition).getGoods_price()));
					entity.setGoods_status(data.get(realPosition).getGoods_status());
					entity.setId(data.get(realPosition).getId());
					entity.setIs_down_line(data.get(realPosition).getIs_down_line());
					entity.setLimit_buy_num(data.get(realPosition).getLimit_buy_num());
					entity.setOpen_time(data.get(realPosition).getOpen_time());
					entity.setParent_id(data.get(realPosition).getParent_id());
					//entity.setRecord(data.get(realPosition).getr);
					entity.setSurplus(data.get(realPosition).getBuy_num());
					entity.setType_id(data.get(realPosition).getType_id());
					//cartProvider.put(entity);
					//Toast.makeText(mContext, "已加入到购物车",0).show();
					// Toast.LENGTH_SHORT).show();
					//click.onCartClick(data.get(realPosition).getId(),data.get(realPosition).getExpect(),data.get(realPosition));
					addShoppingCart(data.get(realPosition).getGoods_id(), data.get(realPosition).getExpect(), entity);
					if(!Values.idList.contains(entity.getGoods_id())){
						Values.idList.add(entity.getGoods_id());
						if (MainActivity.badgeView.isShown()) {
							MainActivity.badgeView.increment(1);
						} else {
							MainActivity.badgeView.show();
						}
					}
				}
			});
			
((LimShopHolder) viewHolder).shop_imgbt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					/*if (holderListener != null) {
						int[] start_location = new int[2];
						((LimShopHolder) viewHolder).image_img.getLocationInWindow(start_location);// 获取点击商品图片的位置
						Drawable drawable = ((LimShopHolder) viewHolder).image_img.getDrawable();// 复制一个新的商品图标
						// mHolderClickListener.onHolderClick(drawable,start_location);
						holderListener.SetOnClinck(drawable, start_location);
					}*/
					//DataEntity dataa = data.get(realPosition);
					ListEntity entity = new ListEntity();
					String s = data.get(realPosition).getAuto_release();
					entity.setAuto_release(s);
					entity.setCover_img(data.get(realPosition).getCover_img().get(0));
					String t = data.get(realPosition).getExpect();
					entity.setExpect(t);
					List<String> r = data.get(realPosition).getCover_img();
					entity.setFace_img(r );
					entity.setGoods_expect(data.get(realPosition).getGoods_expect());
					entity.setGoods_id(data.get(realPosition).getGoods_id());
					entity.setGoods_info(data.get(realPosition).getGoods_info());
					entity.setGoods_name(data.get(realPosition).getGoods_name());
					entity.setGoods_price(Double.parseDouble(data.get(realPosition).getGoods_price()));
					entity.setGoods_status(data.get(realPosition).getGoods_status());
					entity.setId(data.get(realPosition).getId());
					entity.setIs_down_line(data.get(realPosition).getIs_down_line());
					entity.setLimit_buy_num(data.get(realPosition).getLimit_buy_num());
					entity.setOpen_time(data.get(realPosition).getOpen_time());
					entity.setParent_id(data.get(realPosition).getParent_id());
					//entity.setRecord(data.get(realPosition).getr);
					entity.setSurplus(data.get(realPosition).getBuy_num());
					entity.setType_id(data.get(realPosition).getType_id());
					//cartProvider.put(entity);
					//Toast.makeText(mContext, "已加入到购物车",0).show();
					// Toast.LENGTH_SHORT).show();
					//click.onCartClick(data.get(realPosition).getId(),data.get(realPosition).getExpect(),data.get(realPosition));
					addShoppingCartAndGoToShopping(data.get(realPosition).getGoods_id(), data.get(realPosition).getExpect(), entity);
					/*if (MainActivity.badgeView.isShown()) {
						MainActivity.badgeView.increment(1);
					} else {
						MainActivity.badgeView.show();
					}*/
				}
			});
			
			((LimShopHolder) viewHolder).ll.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(mContext, "funduzi" + realPosition, 0).show();
					ListEntity entity = new ListEntity();
					String s = data.get(realPosition).getAuto_release();
					entity.setAuto_release(s);
					entity.setCover_img(data.get(realPosition).getCover_img().get(0));
					String t = data.get(realPosition).getExpect();
					entity.setExpect(t);
					List<String> r = data.get(realPosition).getCover_img();
					entity.setFace_img(r );
					entity.setGoods_expect(data.get(realPosition).getGoods_expect());
					entity.setGoods_id(data.get(realPosition).getGoods_id());
					entity.setGoods_info(data.get(realPosition).getGoods_info());
					entity.setGoods_name(data.get(realPosition).getGoods_name());
					entity.setGoods_price(Double.parseDouble(data.get(realPosition).getGoods_price()));
					entity.setGoods_status(data.get(realPosition).getGoods_status());
					entity.setId(data.get(realPosition).getId());
					entity.setIs_down_line(data.get(realPosition).getIs_down_line());
					entity.setLimit_buy_num(data.get(realPosition).getLimit_buy_num());
					entity.setOpen_time(data.get(realPosition).getOpen_time());
					entity.setParent_id(data.get(realPosition).getParent_id());
					//entity.setRecord(data.get(realPosition).getr);
					entity.setSurplus(data.get(realPosition).getBuy_num());
					entity.setType_id(data.get(realPosition).getType_id());
					Intent i = new Intent(mContext, ProductDeTimeActivity.class);
					i.putExtra("listEntity", entity);
					mContext.startActivity(i);
				}
			});
		}
	}

	protected void addShoppingCart(String goods_id, String expect, final ListEntity entity) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("app", "1");
			json.put("model", "BuyRecord");
			json.put("function", "addCarList");
			json.put("code", goods_id + "," + expect );
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		if(Values.cookieStore == null){
		DefaultHttpClient httpClient = (DefaultHttpClient) utils.getHttpClient();
		Values.cookieStore = httpClient.getCookieStore();
		}else{
			utils.configCookieStore(Values.cookieStore);
		}
		utils.send(HttpMethod.POST, OApi.Public_appPort, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, arg1, 0).show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					int status = jso.getInt("status");
					//Toast.makeText(mContext, "status=" + status + "\ndata=" + jso.getString("data"), 0).show();
					if(status == 1){
						Toast.makeText(mContext, "已添加到购物车！", 0).show();
						cartProvider.put(entity);
						if(!Values.idList.contains(entity.getGoods_id())){
							Values.idList.add(entity.getGoods_id());
							if (MainActivity.badgeView.isShown()) {
								MainActivity.badgeView.increment(1);
							} else {
								MainActivity.badgeView.show();
							}
						}
					}else if(status == 0){
						Toast.makeText(mContext, jso.getString("data"), 0).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	protected void addShoppingCartAndGoToShopping(String goods_id, String expect, final ListEntity entity) {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		try {
			json.put("app", "1");
			json.put("model", "BuyRecord");
			json.put("function", "addCarList");
			json.put("code", goods_id + "," + expect );
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		RequestParams params = new RequestParams();
		try {
			params.setBodyEntity(new StringEntity(json.toString(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpUtils utils = new HttpUtils();
		if(Values.cookieStore == null){
		DefaultHttpClient httpClient = (DefaultHttpClient) utils.getHttpClient();
		Values.cookieStore = httpClient.getCookieStore();
		}else{
			utils.configCookieStore(Values.cookieStore);
		}
		utils.send(HttpMethod.POST, OApi.Public_appPort, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, arg1, 0).show();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				String result = arg0.result;
				try {
					JSONObject jso = new JSONObject(result);
					int status = jso.getInt("status");
					//Toast.makeText(mContext, "status=" + status + "\ndata=" + jso.getString("data"), 0).show();
					if(status == 1){
						Toast.makeText(mContext, "已添加到购物车！", 0).show();
						cartProvider.put(entity);
						Intent intent = new Intent(mContext, MainActivity.class);
						intent.putExtra("tag", 3);
						mContext.startActivity(intent);
						if(!Values.idList.contains(entity.getGoods_id())){
							Values.idList.add(entity.getGoods_id());
							if (MainActivity.badgeView.isShown()) {
								MainActivity.badgeView.increment(1);
							} else {
								MainActivity.badgeView.show();
							}
						}
					}else if(status == 0){
						Toast.makeText(mContext, jso.getString("data"), 0).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	class LimShopHolder extends BaseRecyclerAdapter.Holder {

		private ImageView image_img;
		private TextView count_tx, left_tx, total_tx;
		private TextView price_tx;
		private ProgressBar count_Pro;
		private ImageButton shop_imgbt, cart_imgbt;
		private LinearLayout ll;
		private TextView item_limshop_xg;

		public LimShopHolder(View itemView) {
			super(itemView);
			image_img = (ImageView) itemView.findViewById(R.id.itemhome_image_img);
			price_tx = (TextView) itemView.findViewById(R.id.itemhome_price_tx);
			count_Pro = (ProgressBar) itemView.findViewById(R.id.itemhome_count_Pro);
			count_tx = (TextView) itemView.findViewById(R.id.itemhome_count_tx);
			left_tx = (TextView) itemView.findViewById(R.id.itemhome_left_tx);
			total_tx = (TextView) itemView.findViewById(R.id.itemhome_total_tx);
			shop_imgbt = (ImageButton) itemView.findViewById(R.id.itemhome_shop_imgbt);
			cart_imgbt = (ImageButton) itemView.findViewById(R.id.itemhome_cart_imgbt);
			ll = (LinearLayout) itemView.findViewById(R.id.itemhome_recom_lay);
			item_limshop_xg = (TextView) itemView.findViewById(R.id.item_limshop_xg);
		}

	}
	
	public void SetViewHolderListener(SetHolderListener holderListener) {
		this.holderListener = holderListener;
	}

	public interface SetHolderListener {
		void SetOnClinck(Drawable drawable, int[] start_location);
	}

	
	public void setOnCartClickListener(OnCartClick click) {
		this.click = click;
	}

	public interface OnCartClick {
		public void onCartClick(String id,String expect,Serializable sb);
	}
	
}
